package com.core.web.struts2.taglib;

import java.util.List;

import org.apache.struts2.views.jsp.*;

import com.core.configuration.*;
import com.core.cache.CommonCache;
import com.core.cache.Common;

import javax.servlet.jsp.*;

/**
 * Select JSP 标签
 * 
 * 
 */
public class SelectTag extends CommonTag {

	protected boolean emptyOption = false;
	protected boolean multiple = false;
	protected String cachename;

	@Override
	public int doStartTag() throws JspException {
		return SKIP_BODY;
	}

	@Override
	public int doEndTag() throws javax.servlet.jsp.JspException {
		try {
			pageContext.getOut().print(getHtml());
		} catch (Exception e) {
			throw new JspException(e);
		}
		return EVAL_BODY_INCLUDE;
	}

	private String getHtml() {
		StringBuffer ret = new StringBuffer(" <select ");

		ret.append(this.getCommonHtml());

		if (this.multiple) {
			ret.append(" multiple ");
		}

		if (this.emptyOption) {
			ret.append(" emptyOption=\"true\" ");
		}

		ret.append(" >");

		if (this.emptyOption) {
			ret.append("<option value=\"\">---").append(
					Configuration.CHOOSE_INFO).append("---</option>");
		}

		Object stackObject = TagUtils.getStack(this.pageContext)
				.findValue(name);
		String inputValue = "";

		if (getValue() != null && !getValue().equals("")) {
			inputValue = getValue();
		}
		if (stackObject != null && !stackObject.equals("")) {
			inputValue = stackObject.toString();
		}

		/**
		 * 从通用缓存中取出相应的缓存信息列表，默认与值匹配的选项选中
		 */
		if (this.cachename != null && !this.cachename.equals("")) {
			List<Common> datas = CommonCache.getInstance().getCommon(
					this.cachename);
			if (datas != null && !datas.isEmpty()) {
				for (Common data : datas) {
					ret
							.append("<option value=\"")
							.append(data.getKey())
							.append("\"")
							.append(
									data.getKey().equals(inputValue) ? "selected"
											: "").append(">").append(
									data.getValue()).append("</option>");
				}
			}
		}

		ret.append("</select>");

		if (this.datatype != null && this.datatype.equals("Require")) {
			ret.append("<font color='red'>*</font>");
		}

		return ret.toString();
	}

	public boolean isEmptyOption() {
		return emptyOption;
	}

	public void setEmptyOption(boolean emptyOption) {
		this.emptyOption = emptyOption;
	}

	public boolean isMultiple() {
		return multiple;
	}

	public void setMultiple(boolean multiple) {
		this.multiple = multiple;
	}

	public String getCachename() {
		return cachename;
	}

	public void setCachename(String cachename) {
		this.cachename = cachename;
	}
}
